package com.blueheart.music.controller;

import com.blueheart.music.common.ResultUtil;
import com.blueheart.music.consts.MyConst;
import com.blueheart.music.exception.BaseException;
import com.blueheart.music.exception.BaseExceptionEnum;
import com.blueheart.music.model.pojo.Admin;
import com.blueheart.music.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class AdminController {
    @Autowired
    private AdminService adminService;

    /**
     * 用户登录
     * @param name
     * @param password
     * @return
     * @throws BaseException
     */
    @PostMapping("/admin/login")
    @ResponseBody
    public ResultUtil adminLogin(HttpSession httpSession, @RequestParam("name") String name, @RequestParam("password") String password) throws BaseException {
       if (StringUtils.isEmpty(name)){
           return ResultUtil.error(BaseExceptionEnum.NAME_NULL);
       }
        if (StringUtils.isEmpty(password)){
            return ResultUtil.error(BaseExceptionEnum.PASSWORD_NULL);
        }
        Admin admin=adminService.login(name,password);
       if (admin==null){
           return ResultUtil.error(BaseExceptionEnum.LOGIN_ERROR);
       }
       httpSession.setAttribute(MyConst.ADMIN,admin);
        return ResultUtil.success(admin);
    }

    /**
     * 退出登录
     * @param httpSession
     * @return
     */
    @PostMapping("/admin/logout")
    @ResponseBody
    public ResultUtil adminLogout(HttpSession httpSession){
        Admin admin =(Admin) httpSession.getAttribute(MyConst.ADMIN);
        if (admin==null){
            return ResultUtil.error(BaseExceptionEnum.LOGOUT_ERROR);
        }
        httpSession.removeAttribute(MyConst.ADMIN);
        return ResultUtil.success();
    }
}
